//
//  YWDoDeteAndUpKeepMissionTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/10.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWDoDeteAndUpKeepMissionTableViewController.h"
#import "YWDoDeteAndUpKeepEquTypeTableViewController.h"
#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"

#import "YWWriteRuntimeCell.h"
#import "YWDropDownRunTimeCell.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"
#import "YWRuleTableViewCell.h"
#import "YWPostTroubleInfoCell.h"
#import "YWSaveButtonCell.h"
#import "YWPostTroubleTableViewController.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"
#import "YWShowPostTroubleInfoTableViewController.h"

#import "YWEquipmentManager.h"
#import "YWEquipment.h"
#import "YWDictEquipmentRule.h"
#import "YWMissionRuleResult.h"
#import "YWEquipmentMaintenanceRecord.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWEquipmentType.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"
#import "YWResourceManager.h"
#import "YWNotifyManager.h"
#import "YWEquipmentFieldRecord.h"
#import "YWDBTool.h"
#import "YWDetectAndUpkeepManager.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"

@interface YWDoDeteAndUpKeepMissionTableViewController ()<YWTakePhotoCellDelegate,YWSaveButtonCellDelegate>
//选中的设备
@property (nonatomic, strong) YWEquipment *currentEquipment;
//规则
@property (nonatomic, strong) NSMutableArray* missionRuleResults;
//规则内容
@property (nonatomic, strong) NSString* missionRuleContent;

//tableView的footView
@property (nonatomic, strong) UIView* footView;

@property (nonatomic, weak) MBProgressHUD* HUD;
//报障按钮
@property (nonatomic, strong) UIButton *myTroublesButton;
//提交按钮
@property (nonatomic, strong) UIButton *finishedButton;

//@property (nonatomic, strong) NSArray *allEquipments;
//@property (nonatomic, strong) NSMutableArray *recordEquipmentIds;
//@property (nonatomic, strong) NSMutableArray *missionEquipmntIds;
//点击保存按钮的设备
//@property (nonatomic, strong) NSMutableArray *saveEquipmentArray;
//报障设备记录数组
//@property (nonatomic, strong) NSMutableArray *postTroubleRecordArray;
//扫描进入任务页面时的时间
@property (nonatomic, assign) NSTimeInterval clientScanTime;
@end

@implementation YWDoDeteAndUpKeepMissionTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:_maintenanceMission.maintenanceTypeId];
    self.title = typeName;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    _clientScanTime = [[NSDate date] timeIntervalSince1970]*1000;
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerClass:[YWWriteRuntimeCell class] forCellReuseIdentifier:YWWriteRuntimeCellIdentifier];
    [self.tableView registerClass:[YWDropDownRunTimeCell class] forCellReuseIdentifier:YWDropDownRunTimeCellIdentifier];
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    [self.tableView registerClass:[YWSaveButtonCell class] forCellReuseIdentifier:YWSaveButtonCellIdentifier];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showTipsWhenFirstEnter];
    });
    
}
//- (NSMutableArray *)recordEquipmentIds{
//    if (!_recordEquipmentIds) {
//        NSDictionary* recordsDir = [YWDetectAndUpkeepManager detectAndUpkeepRecordsWithMission:_maintenanceMission];
//        _recordEquipmentIds = [NSMutableArray array];
//        for (NSNumber* locationIdNumber in recordsDir.allKeys) {
//            NSArray* records = [recordsDir objectForKey:locationIdNumber];
//            if (_maintenanceMission.equipments.count>0) {//_maintenanceMission.type == YWMissionTypeAuto
//                [records enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
//                    NSString *equipmentId = [dic objectForKey:@"equipmentId"];
//                    YWEquipmentMaintenanceRecord* record = (YWEquipmentMaintenanceRecord*)[dic objectForKey:@"record"];
//                    if (equipmentId.length && [record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
//                        [_recordEquipmentIds addObject:equipmentId];
//                    }
//                }];
//            }else{
//                [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord*  _Nonnull record, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if ([record isKindOfClass:[YWEquipmentMaintenanceRecord class]]) {
//                        if (record.equipmentId) {
//                            [_recordEquipmentIds addObject:record.equipmentId];
//                        }
//                    }
//                }];
//            }
//        }
//    }
//    return _recordEquipmentIds;
//}

//- (NSMutableArray *)missionEquipmntIds{
//    if (!_missionEquipmntIds) {
//        _missionEquipmntIds = [NSMutableArray array];
//    }
//    return _missionEquipmntIds;
//}

//- (NSMutableArray *)saveEquipmentArray{
//    if (!_saveEquipmentArray) {
//        _saveEquipmentArray = [NSMutableArray array];
//    }
//    return _saveEquipmentArray;
//}

//- (void)setMaintenanceMission:(YWMaintenanceMission *)maintenanceMission{
//    _maintenanceMission = maintenanceMission;
//    if (_qrCodeId) {
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
//    }else if (_locationId){
//        _allEquipments = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
//    }
//    
//    NSArray *missionEquipments = nil;
//    if (_maintenanceMission.equipments.count) {
//        missionEquipments = _maintenanceMission.equipments;
//    }else{
//        missionEquipments = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId orLocationId:_locationId equipmentTypeId:_maintenanceMission.equipmentTypeId];
//    }
//    
//    [_allEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
//        [missionEquipments enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull missionEqu, NSUInteger idx, BOOL * _Nonnull equStop) {
//            if ([missionEqu.equipmentId isEqualToString:equipment.equipmentId] && ![self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                if (_currentEquipment == nil) {
//                    _currentEquipment = equipment;
//                }
//                if (equipment.equipmentId) {
//                    [self.missionEquipmntIds addObject:equipment.equipmentId];
//                    //自动保存要做的设备
//                    [self.saveEquipmentArray addObject:equipment];
//                }
//            }
//        }];
//        NSArray *runTimeParameterArray = [[YWEquipmentManager shareManager] equipmentFieldsWithTypeId:equipment.equipmentTypeId maintenanceTypeId:maintenanceMission.maintenanceTypeId];
//        equipment.runTimeParameterArray = runTimeParameterArray.count?runTimeParameterArray:nil;
//    }];
//}

- (void)setAllEquipments:(NSArray *)allEquipments{
    _allEquipments = allEquipments;
    _currentEquipment = _allEquipments[0];
}

- (NSMutableArray *)missionRuleResults
{
    if (!_missionRuleResults) {
        
        NSMutableArray* missionRuleResults = [[NSMutableArray alloc] init];
        NSArray* equipmentRules = [[YWEquipmentManager shareManager] rulesWithEquipmentTypeId:_maintenanceMission.equipmentTypeId maintenanceTypeId:_maintenanceMission.maintenanceTypeId maintenanceCycleId:_maintenanceMission.missionCycle];
        
        [equipmentRules enumerateObjectsUsingBlock:^(YWDictEquipmentRule* _Nonnull rule, NSUInteger idx, BOOL* _Nonnull stop) {
            YWMissionRuleResult* missionRuleResult = [[YWMissionRuleResult alloc] init];
            missionRuleResult.content = rule.content;
            [missionRuleResults addObject:missionRuleResult];
        }];
        _missionRuleResults = missionRuleResults;
    }
    return _missionRuleResults;
}

- (NSString *)missionRuleContent{
    if (!_missionRuleContent) {
        NSString *string = nil;
        NSArray *ruleArray = self.missionRuleResults;
        BOOL haveRule = ruleArray.count > 0 ? YES : NO;
        NSMutableString *ruleContent = [NSMutableString string];
        
        for (int i = 0; i < (haveRule ? ruleArray.count : 1); i++) {
            if (haveRule) {
                YWMissionRuleResult* missionRuleResult = ruleArray[i];
                string = [NSString stringWithFormat:@"%d.%@", i + 1, missionRuleResult.content];
            }else {
                string = NSLocalizedString(@"none", nil);
            }
            if (i != 0) {
                [ruleContent appendString:@"\n"];
            }
            [ruleContent appendString:string];
        }
        _missionRuleContent = [NSString stringWithFormat:@"%@",ruleContent];
    }
    return _missionRuleContent;
}


- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH/2-20*2;
//      报障
        _myTroublesButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _myTroublesButton.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        _myTroublesButton.layer.masksToBounds = YES;
        _myTroublesButton.layer.cornerRadius = 5.0;
        
        [_myTroublesButton setTitle:NSLocalizedString(@"postTrouble", nil) forState:UIControlStateNormal];
        [_myTroublesButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _myTroublesButton.backgroundColor = [UIColor customRedColor];
        [_myTroublesButton addTarget:self action:@selector(cliclPostTroubleEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_myTroublesButton];
//      完成
        _finishedButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _finishedButton.frame = CGRectMake(20*2+_myTroublesButton.bounds.size.width+20, 30, buttonWidth, kButtonH);
        _finishedButton.layer.masksToBounds = YES;
        _finishedButton.layer.cornerRadius = 5.0;
        
        [_finishedButton setTitle:NSLocalizedString(@"finish", nil) forState:UIControlStateNormal];
        [_finishedButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _finishedButton.backgroundColor = [UIColor customBlueColor];
        [_finishedButton addTarget:self action:@selector(clickFinishButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:_finishedButton];
    }
    return _footView;
}

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //选择设备
        return UITableViewAutomaticDimension;//44;
    }else if (indexPath.section==1) {
        //检测保养
        return UITableViewAutomaticDimension;//[YWRuleTableViewCell cellHeightOfRuleContent:self.missionRuleContent];
    }else if (indexPath.section == 2){
        //运行参数
        return _currentEquipment.runTimeParameterArray.count ? 75 : 44;
    }else if (indexPath.section ==3) {
        //备注
        return 90;
    }else{// if (indexPath.section == 4)
        //拍照(高度是动态变化的)
        if (indexPath.row == 0) {
            CGFloat imageH = YWPhotoSize*(_currentEquipment.totalImageNameArray.count/4+1) + YWPhotoGap*(_currentEquipment.totalImageNameArray.count/4);
            return 10*2 + imageH;
        }else{
            return UITableViewAutomaticDimension;//44;
        }

    }
//    else{
//        //报障设备
//        return _postTroubleRecordArray.count>0 ? 54 : 44;
//    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return _allEquipments.count;
    }else if (section==2){
        return _currentEquipment.runTimeParameterArray.count?:1;
    }else if(section==4){
        return 2;
    }else
        return 1;
//    else if (section==5){
//        return _postTroubleRecordArray.count?:1;
//    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"YWDoDeteAndUpKeepMissionTableViewControllerIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        YWEquipment *equipment = self.allEquipments[indexPath.row];
        cell.textLabel.text = equipment.equipmentName?:@"";
        cell.detailTextLabel.text = [self.saveEquipmentArray containsObject:equipment] ? @"已保存" : nil;
        
        if ([equipment.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
//        if ([self.missionEquipmntIds containsObject:equipment.equipmentId]) {
//            if ([self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                cell.textLabel.textColor = [UIColor customTextGrayColor];
//            }else{
//                cell.textLabel.textColor = [UIColor blackColor];
//            }
//        }else{
//            cell.textLabel.textColor = [UIColor customTextGrayColor];
//        }
        return cell;
    }else if (indexPath.section == 1){
        
        YWRuleTableViewCell *cell = [YWRuleTableViewCell cellWithTableView:tableView];
        cell.ruleContent = self.missionRuleContent;
        return cell;
    }else if (indexPath.section == 2){
        YWRunTimeParameter *runTimeParameter = _currentEquipment.runTimeParameterArray.count ? _currentEquipment.runTimeParameterArray[indexPath.row]:nil;
        if (runTimeParameter.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
            YWDropDownRunTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWDropDownRunTimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }else{
            YWWriteRuntimeCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteRuntimeCellIdentifier];
            cell.runTimeParameter = runTimeParameter;
            return cell;
        }
    }else if (indexPath.section == 3){
        YWWriteNoteCell * cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.equipment = _currentEquipment;
        return cell;
    }else{// if (indexPath.section == 4)
        if (indexPath.row==0) {
            YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
            cell.totalImageNameArray = _currentEquipment.totalImageNameArray;
            cell.delegate = self;
            return cell;
        }else{
            YWSaveButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:YWSaveButtonCellIdentifier];
            cell.delegate = self;
            cell.isSave = [self.saveEquipmentArray containsObject:_currentEquipment] ? YES :NO;
            return cell;
        }
    }
//    else{
//        YWPostTroubleInfoCell *cell = [YWPostTroubleInfoCell cellWithTableView:tableView];
//        YWReportTroubleModel *reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
//        cell.reportTrouble = reportTrouble;
//        return cell;
//    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWEquipment *equipment = self.allEquipments[indexPath.row];
//        if ([self.missionEquipmntIds containsObject:equipment.equipmentId]) {
//            if ([self.recordEquipmentIds containsObject:equipment.equipmentId]) {
//                [YWCommonTool showTextHUDWithContent:@"该设备已完成"];
//            }else{
//
        if (_currentEquipment && _currentEquipment.equipmentTypeId != equipment.equipmentTypeId) {
            self.missionRuleContent = nil;
            self.missionRuleResults = nil;
        }
        _currentEquipment = equipment;
//            }
//        }else{
//            [YWCommonTool showTextHUDWithContent:@"不是该任务的设备"];
//        }
        [self.tableView  reloadData];
    }
//    else if (indexPath.section==5) {
//        YWReportTroubleModel *reportTrouble = _postTroubleRecordArray.count>0?_postTroubleRecordArray[indexPath.row]:nil;
//        if (reportTrouble) {
//            YWShowPostTroubleInfoTableViewController *showPostTroubleVC = [[YWShowPostTroubleInfoTableViewController alloc] init];
//            showPostTroubleVC.reportTrouble = reportTrouble;
//            showPostTroubleVC.delegate = self;
//            [self.navigationController pushViewController:showPostTroubleVC animated:YES];
//        }
//     }
}

#pragma mark - tableView.headerView

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWDoDeteAndUpKeepMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;

}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
   
    if (section == 0) {
        return NSLocalizedString(@"selectEquipment", nil);//@"选择设备";
    }else if (section==1){
        NSString *typeName = [YWCommonTool maintenanceTypeOfMaintenanceTypeId:_maintenanceMission.maintenanceTypeId];
        return [NSString stringWithFormat:@"%@%@",typeName,NSLocalizedString(@"item", nil)];
    }else if (section==2){
        return NSLocalizedString(@"runtimeParameter", nil);//@"运行参数";
    }else if (section==3){
        return NSLocalizedString(@"note", nil);//@"备注";
    }else{//if (section==4)
        return NSLocalizedString(@"takePhotoToUpload", nil);//@"拍照上传";
    }
//    else{
//       return @"报障设备";
//    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    _currentEquipment.totalImageNameArray = arr;
    [self.tableView reloadData];
}

//#pragma mark - clickCancelThePostTroubleMissionDelegate
//- (void)clickCancelTheReportTrouble:(YWReportTroubleModel*)reportTrouble{
//    if ([_postTroubleRecordArray containsObject:reportTrouble]) {
//        [[YWReportTroubleManager shareManager] deleteReportTroubleWithTroubleId:reportTrouble.troubleId orUniqueTag:reportTrouble.uniqueTag];
//        [_postTroubleRecordArray removeObject:reportTrouble];
//        [self.tableView reloadData];
//    }
//}

#pragma mark - YWSaveButtonCellDelegate
- (void)clickCancelButtonEvent:(UIButton *)button{
    if ([self.saveEquipmentArray containsObject:_currentEquipment]) {
        [self.saveEquipmentArray removeObject:_currentEquipment];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView reloadData];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"cancelSaveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"operationFailed", nil)];
    }
    
}
- (void)clickSaveButtonEvent:(UIButton *)button{
    NSInteger unfinishCount = _maintenanceMission.equipmentQuantity - _maintenanceMission.completedQuantity;
    if (_currentEquipment && ![_saveEquipmentArray containsObject:_currentEquipment] && _saveEquipmentArray.count == unfinishCount) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"theTotalNumberOfTasksReached", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:_currentEquipment.psText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_currentEquipment.psText.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    
    __block BOOL isRequire = YES;
    [_currentEquipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
        if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
            isRequire = NO;
            *fieldStop = YES;
        }
    }];
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    
    if (_currentEquipment) {
        if (![self.saveEquipmentArray containsObject:_currentEquipment]) {
            [self.saveEquipmentArray addObject:_currentEquipment];
        }
        [self.tableView reloadData];
        //下面这个刷新会导致调用cell的initWithStyle就重新构建了cell，导致图片消失
        //[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:4] withRowAnimation:UITableViewRowAnimationNone];
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"saveSucceed", nil)];
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"noEquipmentToSelect", nil)];
    }
}

//#pragma mark - YWPostTroubleVCDelegate
//- (void)passBackReportTrouble:(YWReportTroubleModel*)reportTrouble{
//    //报修记录
//    if (!_postTroubleRecordArray) {
//        _postTroubleRecordArray = [NSMutableArray array];
//    }
//    if (reportTrouble) {
//        [_postTroubleRecordArray addObject:reportTrouble];
//        [self.tableView reloadData];
//    }
//}

#pragma mark - buttonAction
- (void)cliclPostTroubleEvent:(UIButton *)sender{
    NSArray *allEquipmentArray = nil;
    if (_allEquipments) {
        allEquipmentArray = _allEquipments;
    }else if(_qrCodeId) {
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithQrcodeId:_qrCodeId];
    }else if (_locationId){
        allEquipmentArray = [[YWEquipmentManager shareManager] equipmentWithLocationId:_locationId];
    }
//    YWEquipment *currentEqu = nil;
//    if (_currentEquipment && allEquipmentArray.count) {
//        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K == %@", @"equipmentId", _currentEquipment.equipmentId];
//        NSArray *array = [allEquipmentArray filteredArrayUsingPredicate:searchPredicate];
//        if (array.count>=1) {
//            currentEqu = array[0];}
//    }
    YWPostTroubleTableViewController * postTroublevc = [[YWPostTroubleTableViewController alloc] init];
    postTroublevc.currentEquipment = allEquipmentArray.count ? allEquipmentArray[0] : nil;//currentEqu ? currentEqu:(allEquipmentArray.count ? allEquipmentArray[0] : nil);
    postTroublevc.equipmentArray = allEquipmentArray;
    postTroublevc.qrCodeId = _qrCodeId;
    postTroublevc.locationId = _locationId;
    postTroublevc.shouldPopBack = YES;
    postTroublevc.delegate = (id<YWPostTroubleVCDelegate>)self.doDeteAndUpKeepEquTypeVC;
    [self.navigationController pushViewController:postTroublevc animated:YES];
}

- (void)clickFinishButtonEvent:(UIButton *)sender{
    [self.view endEditing:YES];
    
    NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"equipmentTypeId", _currentEquipment.equipmentTypeId];
    NSArray *currentSaveArray = [[self.saveEquipmentArray filteredArrayUsingPredicate:searchPredicate] mutableCopy];
    
    if (currentSaveArray.count==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"pleaseSaveTheWritings", nil)];
        return;
    }
    if ([YWCommonTool isContainsEmoji:_currentEquipment.psText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_currentEquipment.psText.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    __block BOOL isRequire = YES;
    __block NSString *reasonable = nil;
    __block BOOL containEmoji = NO;
    [currentSaveArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([YWCommonTool isContainsEmoji:equipment.psText]) {
            containEmoji = YES;
            *stop = YES;
        }
        if (equipment.psText.length > 100) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
            return;
        }
        [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull fieldStop) {
            if (field.required && field.fieldValue.length==0 && field.fieldOptionValue ==nil) {
                isRequire = NO;
                *fieldStop = YES;
                *stop = YES;
            }else if (field.fieldType.fieldTypeId==YWEquipmentFieldTypeIdNumber && (field.maxFieldValue!=0 || field.minFieldValue!=0) && field.fieldValue.length>0 && ([field.fieldValue integerValue]>field.maxFieldValue||[field.fieldValue integerValue]<field.minFieldValue)) {
                reasonable = [NSString stringWithFormat:@"%@(%@)",field.fieldName,equipment.equipmentName];
                //*stop = YES;
            }else if ([YWCommonTool isContainsEmoji:field.fieldValue]){
                containEmoji = YES;
                *stop = YES;
            }
        }];
    }];
    
    if (!isRequire) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"isRequired", nil)];
        return;
    }
    if (containEmoji) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (reasonable.length>0) {
        NSString *tips = [NSString stringWithFormat:@"%@%@",reasonable,NSLocalizedString(@"valueNotInReasonableRangeAndMakeSureToCommit", nil)];
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:tips preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//- (void)commitRecord{
//    NSString *content = [NSString stringWithFormat:@"提交记录，请确定"];
//    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:content preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
//    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [self.HUD show:YES];
//        //上传报障
//        [self.postTroubleRecordArray enumerateObjectsUsingBlock:^(YWReportTroubleModel*  _Nonnull reportTrouble, NSUInteger idx, BOOL * _Nonnull stop) {
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                NSArray *troublePicureArray = [[YWDBTool shareDBTool] picturesWithMissionId:reportTrouble.troubleId maintenanceType:reportTrouble.maintenanceTypeId];
////                [[YWMissionManager shareManager] startUploadRecords:nil Mission:troubleMission pictures:troublePicureArray];
//                [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:troublePicureArray];
//            });
//        }];
//        
//        _maintenanceMission.completedQuantity = _maintenanceMission.completedQuantity + _saveEquipmentArray.count;
//        _maintenanceMission.finishTime = [[NSDate date] timeIntervalSince1970] * 1000;
//        
//        if (_maintenanceMission.equipmentQuantity <= _maintenanceMission.completedQuantity) {
//            _maintenanceMission.missionStatus = YWMissionStatusFinished;
//        }
//        
//        __block NSArray* equipmentMaintenanceRecords = [self createEquipmentMaintenanceRecords];
//        __block NSArray* pictures = [self createPictureWithRecords:equipmentMaintenanceRecords];
//        __block NSArray* equipmentFields = [self createEquipmentFieldsRecordsWithRecords:equipmentMaintenanceRecords];
//        
//        
//        BOOL saveMission = [YWDetectAndUpkeepManager updateDetectAndUpkeepMissionWithArray:_maintenanceMission? @[ _maintenanceMission ] : nil];
//        BOOL saveMaintenanceRecord = [YWDetectAndUpkeepManager updateMaintenanceRecords:equipmentMaintenanceRecords maintenanceTypeId:_maintenanceMission.maintenanceTypeId];
//        BOOL saveEquipmetFieldRecord = [[YWMissionManager shareManager] updateEquipmentFieldRecords:equipmentFields];
//        
//        BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
//        if (saveMission && saveMaintenanceRecord && savePicturesToDB && saveEquipmetFieldRecord) {
//            [self.HUD hide:YES];
//            //提交记录
//            [[YWDetectAndUpkeepManager alloc] startUploadDetectAndUpkeepRecords:equipmentMaintenanceRecords maintenanceMission:_maintenanceMission pictures:pictures];
//            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [[YWNotifyManager shareManager] postMissionFinishedNotifyWithMission:_maintenanceMission];
//                [self.navigationController popViewControllerAnimated:YES];
//            });
//        }
//        else {
//            [self.HUD hide:YES];
//            YWLog(@"保存数据库失败");
//            [YWCommonTool showTextHUDWithContent:kTextSubmitTaskFail];
//        }
//    }]];
//    [self presentViewController:alertController animated:YES completion:nil];
//}
//
//- (NSArray*)createPictureWithRecords:(NSArray*)records
//{
//    NSMutableArray* pictures = [NSMutableArray array];
//    [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
//        YWEquipment *equipment = _saveEquipmentArray[idx];
//        for (int i = 0; i < [equipment.totalImageNameArray count]; i++) {
//            YWPicture* picture = [[YWPicture alloc] init];
//            picture.pictureId = [YWCommonTool randStringId];
//            picture.pictureName = equipment.totalImageNameArray[i];
//            picture.isLocalImage = YES;
//            picture.uploadStatus = YWPictureUploadStatusNull;
//            picture.missionId = _maintenanceMission.missionId;
//            picture.maintenanceType = _maintenanceMission.maintenanceTypeId;
//            picture.equipmentId = record.equipmentId;
//            picture.recordId = record.recordId;
//            [pictures addObject:picture];
//        }
//    }];
//    return pictures;
//}
//- (NSArray*)createEquipmentMaintenanceRecords
//{
//    NSMutableArray* equipmentMaintenanceRecords = [NSMutableArray array];
//    
//    [_saveEquipmentArray enumerateObjectsUsingBlock:^(YWEquipment* _Nonnull equipment, NSUInteger idx, BOOL* _Nonnull stop) {
//        YWEquipmentMaintenanceRecord* maintenanceRecord = [[YWEquipmentMaintenanceRecord alloc] init];
//        //这里原来有减idx  -idx（改了时间戳的方法后就删掉了）
//        maintenanceRecord.recordId = [YWCommonTool negativeTimestampId] ;
//        /**任务ID*/
//        maintenanceRecord.missionId = _maintenanceMission.missionId;
//        NSString *uniqueTag = [YWCommonTool randStringId];
//        maintenanceRecord.maintenanceTypeId = _maintenanceMission.maintenanceTypeId;
//        maintenanceRecord.uniqueTag = uniqueTag;
//        maintenanceRecord.equipmentId = equipment.equipmentId;
//        maintenanceRecord.note = [equipment.psText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//        maintenanceRecord.completeTime = [[NSDate date] timeIntervalSince1970] * 1000;
//        maintenanceRecord.clientScanTime = _clientScanTime;
//        maintenanceRecord.handlerName = [YWLoginTool loginUser].userName;
//        maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusNormal;
//        maintenanceRecord.uploadStatus = YWEquipmentMaintenanceRecordUploadStatusUploading;
//        
//        NSString *dayMonthString = [YWCommonTool showTime:maintenanceRecord.completeTime / 1000 andFormatter:KTimeFormatDayMonth];
//        maintenanceRecord.dayMonthString = dayMonthString;
//        //检测保养都是正常完成状态，没有故障状态
//        //if (self.postTroubleRecordArray.count>0) {
//            //maintenanceRecord.status = YWEquipmentMaintenanceRecordStatusTrouble;
//        //}
//        
//        [equipmentMaintenanceRecords addObject:maintenanceRecord];
//    }];
//    return equipmentMaintenanceRecords;
//}
//- (NSArray*)createEquipmentFieldsRecordsWithRecords:(NSArray*)records{
//    __block NSMutableArray* fieldsArray = nil;
//    __block NSMutableArray* allFieldRecords = [NSMutableArray array];
//    [records enumerateObjectsUsingBlock:^(YWEquipmentMaintenanceRecord* _Nonnull record, NSUInteger idx, BOOL* _Nonnull stop) {
//        YWEquipment *equipment = _saveEquipmentArray[idx];
//        if ([record.equipmentId isEqualToString:equipment.equipmentId]) {
//            fieldsArray = [[NSMutableArray alloc]init];
//            [equipment.runTimeParameterArray enumerateObjectsUsingBlock:^(YWRunTimeParameter*  _Nonnull field, NSUInteger cusIdx, BOOL * _Nonnull stop) {
//                YWEquipmentFieldRecord *fieldRecord = [[YWEquipmentFieldRecord alloc]init];
//                fieldRecord.uniqueTag = record.uniqueTag;
//                fieldRecord.fieldId = field.fieldId;
//                fieldRecord.fieldName = field.fieldName;
//                if (field.fieldType.fieldTypeId == YWEquipmentFieldTypeIdDownSelect) {
//                    fieldRecord.fieldTypeId = YWEquipmentFieldTypeIdDownSelect;
//                    fieldRecord.fieldOption = field.fieldOptionValue;
//                }else{
//                    fieldRecord.fieldValue = field.fieldValue;
//                }
//                fieldRecord.maintenanceTypeId = _maintenanceMission.maintenanceTypeId;
//                [fieldsArray addObject:fieldRecord];
//                [allFieldRecords addObject:fieldRecord];
//            }];
//            record.equipmentFieldRecord = fieldsArray;
//        }
//    }];
//    return allFieldRecords;
//}

//- (MBProgressHUD*)HUD
//{
//    if (!_HUD) {
//        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
//        hud.labelFont = kHUDLabelFont;
//        hud.labelText = kTextSubmitTask;
//        hud.dimBackground = YES;
//        // hud.animationType = MBProgressHUDAnimationZoom;
//        _HUD = hud;
//        _HUD.tag = kMBProgressHUDTag;
//        [self.navigationController.view addSubview:hud];
//    }
//    return _HUD;
//}

#pragma mark - alert view
- (void)showTipsWhenFirstEnter{
    BOOL notFirstEnter = [[[NSUserDefaults standardUserDefaults] objectForKey:KNotFirstEnterDoMissionVC] boolValue];
    if (!notFirstEnter) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(KFirstEnterDoMissionVCTips, nil) preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"dontPromptAgain", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KNotFirstEnterDoMissionVC];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
